import cv2
import os
from tqdm import tqdm
import shutil


class VideoToolBox:

    def __init__(self):
        pass

    @staticmethod
    def ReadVideoFile(video_file_path):
        video_capture = cv2.VideoCapture(video_file_path)  # 捕捉视频，未开始读取；
        video_fps = video_capture.get(cv2.CAP_PROP_FPS)  # 获取视频帧速率
        video_width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
        video_height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        video_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
        video_size = [video_width, video_height]
        print("fps:", video_fps)
        print("size:", video_size)
        print("count:", video_count)
        return

    @staticmethod
    def WriteVideoFile(read_video_file_path, save_dircetory_path, file_name, file_format_name="mp4"):
        fourcc = None
        if file_format_name == "avi":
            write_video_file_name = file_name + r".avi"
            write_video_file_path = os.path.join(save_dircetory_path, write_video_file_name)
            # fourcc = cv2.VideoWriter_fourcc("X", "V", "I", "D")  # 压缩
            fourcc = cv2.VideoWriter_fourcc("I", "4", "2", "0")  # 未压缩的YUV颜色编码，文件较大
        elif file_format_name == "flv":
            write_video_file_name = file_name + r".flv"
            write_video_file_path = os.path.join(save_dircetory_path, write_video_file_name)
            cv2.VideoWriter_fourcc("F", "L", "V", "1")
        elif file_format_name == "mp4":
            write_video_file_name = file_name + r".mp4"
            write_video_file_path = os.path.join(save_dircetory_path, write_video_file_name)
            fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
        else:
            print("未识别格式！")
            return
        video_capture = cv2.VideoCapture(read_video_file_path)  # 捕捉视频，未开始读取；
        video_fps = video_capture.get(cv2.CAP_PROP_FPS)  # 获取视频帧速率
        video_width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
        video_height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # video_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
        video_size = (video_width, video_height)
        video_write = cv2.VideoWriter(write_video_file_path, fourcc, video_fps, video_size, True)
        t1 = cv2.getTickCount()  # CPU启动后总计数
        success, frame = video_capture.read()  # 读帧
        while success:  # Loop until there are no more frames.
            video_write.write(frame)  # 写视频帧
            success, frame = video_capture.read()  # 获取下一帧
        t2 = cv2.getTickCount()
        print((t2 - t1) / cv2.getTickFrequency())
        video_capture.release()
        video_write.release()
        return

    @classmethod
    def BatchTransformVideoFormat(cls, source_video_folder_path, save_video_folder_path, video_format_name="mp4"):
        """
        批量转换视频格式
        :param source_video_folder_path:
        :param save_video_folder_path:
        :param video_format_name:
        :return:
        """
        video_file_name_list = os.listdir(source_video_folder_path)
        print("共%d个任务" % len(video_file_name_list))
        for list_index, video_file_name in enumerate(video_file_name_list):
            print("正在执行第%d个任务:" % (list_index + 1), video_file_name)
            [file_name, extend] = os.path.splitext(video_file_name)
            source_video_file_path = os.path.join(source_video_folder_path, video_file_name)
            if extend[1:] != video_format_name:
                cls.WriteVideoFile(source_video_file_path, save_video_folder_path, file_name, video_format_name)
            else:
                save_video_file_path = os.path.join(save_video_folder_path, video_file_name)
                shutil.copy(source_video_file_path, save_video_file_path)
        return

    @staticmethod
    def MultipleVideoComposeSingleVideo(multipleVideoFilePathList, singleVideoFilePath):
        tempVideoParams = None
        videoWrite = None
        for listIndex, videoFilePath in enumerate(multipleVideoFilePathList):
            videoCapture = cv2.VideoCapture(videoFilePath)  # 捕捉视频，未开始读取；
            videoFps = videoCapture.get(cv2.CAP_PROP_FPS)  # 获取视频帧速率
            videoWidth = int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH))
            videoHeight = int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
            videoSize = (videoWidth, videoHeight)
            videoParams = [videoFps, videoSize]
            if listIndex == 0:
                tempVideoParams = videoParams
                fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
                singleVideoFps = tempVideoParams[0]
                singleVideoSize = tempVideoParams[1]
                videoWrite = cv2.VideoWriter(singleVideoFilePath, fourcc, singleVideoFps, singleVideoSize, True)
                success, frame = videoCapture.read()
                while success:
                    videoWrite.write(frame)
                    success, frame = videoCapture.read()
                videoCapture.release()
            elif listIndex != 0 and tempVideoParams != videoParams:
                print("视频参数不一致，无法合成！")
                videoCapture.release()
                return
            else:
                success, frame = videoCapture.read()
                while success:
                    videoWrite.write(frame)
                    success, frame = videoCapture.read()
                videoCapture.release()
        videoWrite.release()
        return
